package com.flats.model.dao.hibernate;

import com.flats.model.entity.Owner;
import com.flats.model.entity.Persistent;
import com.flats.model.entity.Users;
import org.hibernate.SQLQuery;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

@Transactional
public class OwnerHibernateDao<T extends Persistent> extends AbstractHibernateDao<Owner> {
    @Override
    @Transactional
    public Serializable saveOrUpdate(Owner persistent) {
        getSession().beginTransaction();
        Serializable id = getSession().save(persistent);
        getSession().getTransaction().commit();
        return id;
    }

    @Override
    @Transactional
    public void delete(Long id) {
        getSession();
        getSession().beginTransaction();
        String query = "delete from ROOT_USER.OWNER where OWNER_ID=" + id.toString();
        SQLQuery sqlQuery = getSession().createSQLQuery(query);
        sqlQuery.executeUpdate();
        getSession().getTransaction().commit();
    }

    @Override
    @Transactional
    public void delete(Owner persistent) {
        if (!getSession().getTransaction().isActive()) {
            getSession().beginTransaction();
        }
        getSession().delete(persistent);
        getSession().getTransaction().commit();
    }

    @Override
    @Transactional
    public Owner get(Long id) {
//        getSession().beginTransaction();
        if (!getSession().getTransaction().isActive()) {
            getSession().beginTransaction();
        }
        return (Owner) getSession().load(Owner.class, id);
    }

    @Override
    @Transactional
    public List<Owner> getAll() {
        if (!getSession().getTransaction().isActive()) {
            getSession().beginTransaction();
        }
        String query = "select * from ROOT_USER.OWNER";
        List<Owner> ownerList = getSession().createSQLQuery(query)
                .addEntity(Owner.class)
                .list();
        return ownerList;
    }
}
